/*
 * @Author: caiyunyun
 * @Date: 2025-01-15 11:29:52
 * @Description:
 */
package logger

import (
	"fmt"
	"os"
	"path/filepath"
	"time"
)

type Logger struct {
	filePrefix string
	file       *os.File
}

var logger *Logger

func init() {

	var err error
	logger, err = NewLogger("mytest")
	if err != nil {
		fmt.Printf("failed to create logger: %v", err)
	}
	defer logger.Close()
}

func NewLogger(filePrefix string) (*Logger, error) {
	logFile, err := createLogFile(filePrefix)
	if err != nil {
		return nil, err
	}
	return &Logger{
		filePrefix: filePrefix,
		file:       logFile,
	}, nil
}

func GetLogger() *Logger {
	return logger
}

func SetLogName(name string) {
	logger.filePrefix = name
}

func createLogFile(filePrefix string) (*os.File, error) {
	fileName := generateFileName(filePrefix)
	return os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
}

func generateFileName(filePrefix string) string {
	now := time.Now()
	hour := now.Format("2006010215")
	return filepath.Join(".", fmt.Sprintf("%s_%s.log", filePrefix, hour))
}

func (l *Logger) Log(message string) error {
	now := time.Now().Format("2006-01-02 15:04:05")
	logMessage := fmt.Sprintf("[%s] %s\n", now, message)
	_, err := l.file.WriteString(logMessage)
	if err != nil {
		return err
	}
	return nil
}

func (l *Logger) Close() error {
	return l.file.Close()
}

func Log(message string) error {
	return logger.Log(message)
}
